using Microsoft.AspNetCore.Mvc;
using SmartCustomerService.Web.Models;
using SmartCustomerService.Web.Services;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;

namespace SmartCustomerService.Web.Controllers;

/// <summary>
/// 阿里云百炼智能客服系统 API 控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class AliyunBailianController : ControllerBase
{
    private readonly IAliyunBailianCustomerService _customerService;
    private readonly ILogger<AliyunBailianController> _logger;

    public AliyunBailianController(
        IAliyunBailianCustomerService customerService,
        ILogger<AliyunBailianController> logger)
    {
        _customerService = customerService;
        _logger = logger;
    }

    /// <summary>
    /// 智能客服对话接口
    /// </summary>
    /// <param name="request">对话请求，包含用户消息</param>
    /// <returns>AI 智能回答</returns>
    /// <response code="200">成功返回 AI 回答</response>
    /// <response code="400">请求参数错误</response>
    /// <response code="500">服务器内部错误</response>
    [HttpPost("chat")]
    [ProducesResponseType(typeof(ChatResponse), 200)]
    [ProducesResponseType(typeof(object), 400)]
    [ProducesResponseType(typeof(ChatResponse), 500)]
    public async Task<IActionResult> Chat([FromBody] ChatRequest request)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(request.Message))
            {
                return BadRequest(new { error = "消息内容不能为空" });
            }

            var response = await _customerService.ChatAsync(request.Message, request.Context);
            
            return Ok(new ChatResponse
            {
                Message = response,
                Timestamp = DateTime.Now,
                Success = true
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in Aliyun Bailian chat endpoint");
            return StatusCode(500, new ChatResponse
            {
                Message = "服务器内部错误，请稍后重试",
                Timestamp = DateTime.Now,
                Success = false
            });
        }
    }

    /// <summary>
    /// 流式智能客服对话接口
    /// </summary>
    /// <param name="request">对话请求</param>
    /// <returns>流式AI回答</returns>
    [HttpPost("chat/stream")]
    public async Task<IActionResult> StreamChat([FromBody] ChatRequest request)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(request.Message))
            {
                return BadRequest(new { error = "消息内容不能为空" });
            }

            // 设置响应头支持流式传输
            Response.Headers.Add("Content-Type", "text/event-stream");
            Response.Headers.Add("Cache-Control", "no-cache");
            Response.Headers.Add("Connection", "keep-alive");

            var response = await _customerService.ChatAsync(request.Message, request.Context);
            
            // 模拟流式响应
            var chunks = SplitIntoChunks(response, 50);
            foreach (var chunk in chunks)
            {
                var data = $"data: {JsonConvert.SerializeObject(new { content = chunk })}\n\n";
                await Response.WriteAsync(data);
                await Response.Body.FlushAsync();
                await Task.Delay(100); // 模拟打字效果
            }
            
            await Response.WriteAsync("data: [DONE]\n\n");
            await Response.Body.FlushAsync();
            
            return new EmptyResult();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in Aliyun Bailian stream chat endpoint");
            return StatusCode(500, new { error = "流式对话失败" });
        }
    }

    /// <summary>
    /// 获取聊天历史记录
    /// </summary>
    /// <returns>聊天记录列表</returns>
    [HttpGet("history")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(typeof(object), 500)]
    public async Task<IActionResult> GetChatHistory()
    {
        try
        {
            var history = await _customerService.GetChatHistoryAsync();
            return Ok(new
            {
                success = true,
                data = history,
                count = history.Count,
                model = "Aliyun Bailian"
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting chat history");
            return StatusCode(500, new { error = "获取聊天历史失败" });
        }
    }

    /// <summary>
    /// 清空聊天历史记录
    /// </summary>
    /// <returns>操作结果</returns>
    [HttpDelete("history")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(typeof(object), 500)]
    public async Task<IActionResult> ClearChatHistory()
    {
        try
        {
            await _customerService.ClearChatHistoryAsync();
            return Ok(new { success = true, message = "聊天历史已清空" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error clearing chat history");
            return StatusCode(500, new { error = "清空聊天历史失败" });
        }
    }

    /// <summary>
    /// 手动开启新话题
    /// </summary>
    [HttpPost("new-topic")]
    public async Task<IActionResult> StartNewTopic()
    {
        try
        {
            await _customerService.StartNewTopicAsync();
            return Ok(new { success = true, message = "已开启新话题" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error starting new topic");
            return StatusCode(500, new { error = "开启新话题失败" });
        }
    }

    /// <summary>
    /// 服务健康检查
    /// </summary>
    /// <returns>服务状态信息</returns>
    [HttpGet("health")]
    [ProducesResponseType(typeof(object), 200)]
    public IActionResult Health()
    {
        return Ok(new
        {
            service = "Aliyun Bailian Smart Customer Service",
            status = "Running",
            timestamp = DateTime.Now,
            version = "1.0.0",
            model = "Aliyun Bailian",
            provider = "Alibaba Cloud"
        });
    }

    /// <summary>
    /// 获取模型信息
    /// </summary>
    /// <returns>模型配置信息</returns>
    [HttpGet("model-info")]
    public IActionResult GetModelInfo()
    {
        return Ok(new
        {
            model = "qwen-turbo",
            provider = "Alibaba Cloud",
            features = new[]
            {
                "中文优化",
                "多轮对话",
                "上下文理解",
                "情感分析",
                "智能推荐"
            },
            capabilities = new[]
            {
                "产品咨询",
                "订单查询",
                "售后服务",
                "投诉处理",
                "技术支持"
            }
        });
    }

    private List<string> SplitIntoChunks(string text, int chunkSize)
    {
        var chunks = new List<string>();
        for (int i = 0; i < text.Length; i += chunkSize)
        {
            var chunk = text.Substring(i, Math.Min(chunkSize, text.Length - i));
            chunks.Add(chunk);
        }
        return chunks;
    }
}


